/*
 * WIDGET PROTOTYPE
 * */
function Widget(){}
function Widget(name,url,target,components,defaultValue){
	this.name = name;
	this.url  = url;
	this.target = target;
	this.components = components;
	$(window).bind( this.name+'change',(function(){this.change()}).bind(this));
	if($.bbq.getState(this.name) != undefined && this.name !=undefined){
		$(window).trigger( this.name+'change');
	}else if(defaultValue != undefined){
		$.bbq.pushState($.deparam(this.name+'='+defaultValue));
	} 

}

Widget.prototype.change = function(args){
	if(this.checkChange(args)){
		this.refresh(args)
		if(this.components != undefined){
			for(var i=0;i<this.components.lenght;i++){
				$(window).trigger( this.components[i].name+'change');
			}
		}
	}
	
}

Widget.prototype.checkChange = function(args){
	if(this.state == undefined){
		this.state = $.bbq.getState(this.name);
		return true;
	}else{
		var actualState = $.bbq.getState(this.name); 
		if(!actualState.equality(this.state)){
			this.state = actualState;
			return true;
		}

	}
	
	return false;
}

Widget.prototype.refresh = function(args){
	var callbackFunction = (function(response){$(this.target).html(response); this.afterDrawing.call();}).bind(this)
	$.ajax({
	    url: this.url,
	    data: $.bbq.getState(this.name),
	    loadingTarget: this.target,
	    success: callbackFunction,
	    dataType:"html"
	});
}

Widget.prototype.afterDrawing = function(args){ alert('sobreescribi este metodo');}


/**
 * FilterWidget
 */
function FiltersWidget(name,url,target,components,defaultValue){
	Widget.call(this,name,url,target,components,defaultValue);
}

FiltersWidget.prototype = new Widget;
FiltersWidget.prototype.constructor = FiltersWidget;

FiltersWidget.prototype.afterDrawing = function(args){
	$('#map').gmap('clearMarkers');
	addMarkers();
	$('.nano').nanoScroller();
}

/**
 * TabsWidget
 */
function TabsWidget(name,url,target,components,defaultValue){
	Widget.call(this,name,url,target,components,defaultValue);
}

TabsWidget.prototype = new Widget;
TabsWidget.prototype.constructor = TabsWidget;

TabsWidget.prototype.refresh = function(args){
	var tab = $('ul.tabs#'+this.name+' > li > a[href="!#'+this.name+"="+$.bbq.getState(this.name)+'"]' );
	tab = $(tab);
	tab.closest( 'ul.tabs').find('li').removeClass("active");
	tab.parent().addClass("active");
	var activeTab = $.bbq.getState(this.name);
	
	$(this.target).load(activeTab);
	$(this.target).fadeIn();
}
